import json
from urllib.parse import urlencode

from wechat import appsecret, appid, token
from tornado.httpclient import HTTPClient
from tornado.web import HTTPError


def get_openid(code):
    client = HTTPClient()
    values = {
        'appid': appid,
        'secret': appsecret,
        'code': code,
        'grant_type': 'authorization_code'
    }
    query = urlencode(values)
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' + query
    response = client.fetch(url)
    response_dict = json.loads(response.body.decode())
    return response_dict['openid']


def auth_encode(redirect_uri):
    values = {'redirect_uri': redirect_uri}
    param = urlencode(values)
    url = 'https://open.weixin.qq.com/connect/oauth2/authorize'
    query = '?appid=%s&%s&response_type=code&scope=snsapi_base&state=123#wechat_redirect' % (appid, param)
    return url + query


def wechat_required(openid):  # decorator
    def decorator(method):
        def wrapper(_self):
            code = _self.get_query_argument('code')
            print('getting openid, code %s' % code)
            current_openid = get_openid(code)
            _self.openid = current_openid
            if openid == current_openid:
                return method(_self)
            else:
                raise HTTPError(400)
        return wrapper
    return decorator
